package com.example.util;

import ch.qos.logback.classic.Logger;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.LoggerFactory;

import java.io.*;
import java.util.Enumeration;
import java.util.zip.ZipEntry;
import java.util.zip.ZipException;
import java.util.zip.ZipFile;
import java.util.zip.ZipOutputStream;

/**
 * 其实docx属于zip的一种，这里只需要操作word/document.xml中的数据，其他的数据不用动
 */
public class XmlToDocx {

	private final static Logger logger = (Logger) LoggerFactory.getLogger(XmlToDocx.class);

	/**
	 *
	 * @param documentFile
	 *            动态生成数据的docunment.xml文件
	 * @param docxTemplate
	 *            docx的模板
	 * @param fileOutputStream
	 *            需要导出的文件路径
	 * @throws ZipException
	 * @throws IOException
	 */

	public static void outDocx(File documentFile, String docxTemplate, FileOutputStream fileOutputStream)
			throws ZipException, IOException {
		ZipFile zipFile = null;
		ZipOutputStream zipout = null;
		try {
			if (StringUtils.isNotBlank(docxTemplate)) {
				File docxFile = new File(docxTemplate);
				zipFile = new ZipFile(docxFile);
				Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries();

				zipout = new ZipOutputStream(fileOutputStream);
				int len = -1;
				byte[] buffer = new byte[1024];
				while (zipEntrys.hasMoreElements()) {
					ZipEntry next = zipEntrys.nextElement();
					InputStream is = zipFile.getInputStream(next);
					// 把输入流的文件传到输出流中 如果是word/document.xml由我们输入
					zipout.putNextEntry(new ZipEntry(next.toString()));
					if ("word/document.xml".equals(next.toString())) {
						InputStream in = new FileInputStream(documentFile);
						while ((len = in.read(buffer)) != -1) {
							zipout.write(buffer, 0, len);
						}
						in.close();
					} else {
						while ((len = is.read(buffer)) != -1) {
							zipout.write(buffer, 0, len);
						}
						is.close();
					}
				}
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
		} finally {
			if (null != zipout) {
				zipout.close();
			}
			if (null != zipFile) {
				zipFile.close();
			}
			if(fileOutputStream != null){
				fileOutputStream.close();
			}
		}
	}
}